package com.kylin.springboot.config;

import com.kylin.springboot.filter.MyFilter;
import com.kylin.springboot.listener.MyListener;
import com.kylin.springboot.servlet.MyServlet;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class MyServerConfig {

    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");//没传入urlMapping,会默认以servelt的类名首字母小写为urlMapping值:myServlet
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());


        //registrationBean.addUrlPatterns("/hello","/myServlet");

        //setUrlPatterns()这是一次性的设置一个集合。
        registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }


    //配置嵌入式的Servlet容器
    //@Bean
    //public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    //    return new EmbeddedServletContainerCustomizer() {
    //
    //        //定制嵌入式的Servlet容器相关的规则
    //        @Override
    //        public void customize(ConfigurableEmbeddedServletContainer container) {
    //            container.setPort(8083);
    //        }
    //    };
    //}

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                factory.setPort(8080);
            }
        };
    }
}
